package com.example.graduation.controller.user;

import com.example.graduation.entity.dto.MapDto;
import com.example.graduation.entity.pojo.Image;
import com.example.graduation.entity.pojo.User;
import com.example.graduation.mapper.MapDtoMapper;
import com.example.graduation.service.ImageService;
import com.example.graduation.service.UserService;
import com.example.graduation.util.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author Jeffery
 * user权限
 */
@RequestMapping("/user")
@Controller
@Slf4j(topic = "UserController")
@Api(tags = "User权限的Controller")

public class UserController {

    @Resource
    private MapDtoMapper mapDtoMapper;
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private UserService userService;
    @Resource
    private ImageService imageService;
    @Resource
    private PdfUtil pdfUtil;

    /**
     * 激活用户
     *
     * @param code 激活码
     * @return html
     */
    @PostMapping("/active/{code}")
    @ApiOperation("激活用户")
    @ApiImplicitParam(name = "code", value = "激活码", defaultValue = "1008611")
    public String activeUser(@Validated @PathVariable("code") String code, Model model) {
        String result = "修改成功！";
        User currentUser = ShiroUtil.getCurrentUser();
        String redisCode = (String) redisUtil.get(StringUtil.REGISTER_PREFIX + currentUser.getEmail());
        if (code.equals(redisCode)) {
            currentUser.setStatus(1);
            currentUser.setUpdateTime(TimeUtil.getCurrentTimeStamp());
            userService.updateById(currentUser);
            log.info("修改成功 : {}", currentUser.getId());
            redisUtil.remove(StringUtil.REGISTER_PREFIX + currentUser.getEmail());
            log.info("移除redis缓存中的激活码成功！");
        } else {
            result = "激活码失效或者激活码错误！";
            log.info("激活码失效或者激活码错误！");
        }
        model.addAttribute("email", ShiroUtil.getUserName());
        model.addAttribute("active_result", result);
        return "";
    }

    /**
     * 修改用户密码
     *
     * @param oldPassword 用户输入老密码
     * @param newPassword 用户输入新密码
     * @return 修改结果
     */
    @PostMapping("/updatePassword")
    @ApiOperation("修改用户密码")
    @ApiImplicitParam(name = "oldPassword", value = "用户密码", defaultValue = "111111")
    @ResponseBody
    public Map<String, Object> updatePassword(@RequestParam("oldPassword") String oldPassword, @RequestParam("newPassword") String newPassword) {
        User currentUser = ShiroUtil.getCurrentUser();

        Map<String, Object> resultMap = new HashMap<>(16);
        String updateMsg = "修改成功！";

        String userId = currentUser.getId();
        log.info("修改用户的ID：{}", userId);
        //先查询原密码是否正确
        boolean flag = Md5Util.validPassword(oldPassword, currentUser.getPassword());

        if (flag) {
            String encryptedPwd = Md5Util.getEncryptedPwd(newPassword);
            currentUser.setPassword(encryptedPwd);
            currentUser.setUpdateTime(new Timestamp(System.currentTimeMillis()));
            userService.updateById(currentUser);
            log.info("密码修改成功！");
        } else {
            updateMsg = "原密码错误！";
        }
        resultMap.put("result_msg", updateMsg);
        log.info("resultMap : {}", resultMap);
        return resultMap;
    }

    /**
     * 根据ID逻辑删除用户
     *
     * @param id 用户ID
     * @return 删除结果
     */
    @PostMapping("/delUser/{id}")
    @ApiOperation("删除用户根据ID")
    @ApiImplicitParam(name = "id", value = "用户id", defaultValue = "")
    public boolean delUser(@PathVariable("id") String id) {
        User currentUser = ShiroUtil.getCurrentUser();
        if (id.equals(currentUser.getId())) {
            currentUser.setUpdateTime(new Timestamp(System.currentTimeMillis()));
            currentUser.setIsDeleted(1);

            userService.updateById(currentUser);
            log.info("删除用户成功! userId : {}", id);
        }
        return false;
    }

    /**
     * 检查有无简历
     *
     * @return boolean
     */
    @GetMapping("/checkHasJianLi")
    @ResponseBody
    @ApiOperation("校验当前用户是否有简历")
    public boolean checkHasJianLi() {
        String userId = ShiroUtil.getUserId();
        log.info("校验有无简历成功 : {}", userId);
        return mapDtoMapper.checkHasJianLi(userId) != null;
    }

    /**
     * HR新增职位  --    需要进行HR认证!!!!!!
     */
    @GetMapping("/toCreateJob")
    @ApiOperation("创建一个工作")
    public String toCreateJob(Model model) {
        //校验HR是否认证
        MapDto mapDto = mapDtoMapper.checkHrIsAuth(ShiroUtil.getUserId());
        if (mapDto != null) {
            log.info("当前用户已经进行hr认证！");
            model.addAttribute("email", ShiroUtil.getUserId());
            return "create";
        } else {
            log.info("当前用户未进行hr认证！");
            model.addAttribute("hr_msg", "请完成HR认证，再进行发布职位！");
            return "bindstep1";
        }
    }

    /**
     * 用户上传简历
     *
     * @param file 上传的文件
     * @return 上传结果
     */
    @PostMapping("/uploadJl")
    @ApiOperation("上传简历")
    @ApiImplicitParam(name = "file", value = "上传的文件")
    @ResponseBody
    @SuppressWarnings("all")
    public Map<String, Object> uploadJl(@RequestParam("file") MultipartFile file) {
        String pdfFormat = "pdf";
        Map<String, Object> resultMap = new HashMap<>(16);

        //获取源文件后缀名
        String fileName = file.getOriginalFilename();
        log.info("fileName : {}", fileName);
        String suffix = FilenameUtils.getExtension(fileName);
        if (pdfFormat.equals(suffix)) {
            try {
                InputStream inputStream = file.getInputStream();
                byte[] bytes = new byte[(int) file.getSize()];
                inputStream.read(bytes);

                Image image = new Image();
                image.setId(UUID.randomUUID().toString());
                image.setUId(ShiroUtil.getUserId());
                image.setBlog(bytes);
                image.setCreateTime(new Timestamp(System.currentTimeMillis()));
                image.setVersion(1);
                image.setIsDeleted(0);
                image.setExc(suffix);

                imageService.save(image);

                log.info("上传文件成功！");
                resultMap.put("result_msg", "上传简历成功！");

            } catch (IOException e) {
                log.error("发生异常了！:{}", e.getMessage());
                resultMap.put("result_msg", "上传简历失败，请重新上传！");
            }
        } else {
            log.error("上传格式不对!");
            resultMap.put("result_msg", "上传文件格式不对");
        }
        return resultMap;
    }

    @GetMapping("/toWebSocket")
    @ApiOperation("跳转至聊天室")
    public String toWebSocket() {
        return "webSocket";
    }
}
